from redis import ConnectionPool, Redis
from sqlalchemy import create_engine
from sqlalchemy.orm.session import Session
from sqlalchemy_utils import database_exists, create_database, drop_database
try: from src.util.entity import *
except: pass


engine = create_engine("mysql+pymysql://root:123456@192.168.131.129/mydb2?charset=utf8mb4",
    echo=True, future=True, )
mysession = Session(engine)
pool = ConnectionPool(host='192.168.131.129', port=6379)
rd = Redis(connection_pool=pool)


if __name__ == "__main__":
    rd.set("aaa", "bbb")
    v = rd.get("aaa")
    if v != None:
        print(v.decode("utf-8"))

    from entity import *
    try:
        drop_database(engine.url)
    except:
        print("删库跑路失败!")
    if not database_exists(engine.url):
        create_database(engine.url, encoding="utf8mb4")
        MyBase.metadata.create_all(engine)
        print("新建数据库成功!")

    # 加两个班级
    cls1, cls2 = 班级(), 班级()
    cls1.班级名 = "计科204"  # type: ignore
    cls2.班级名 = "软件203"  # type: ignore
    mysession.add_all([cls1, cls2])
    mysession.commit()

    # 加一个班主任
    teacher = 班主任()
    teacher.班级id = "1"  # type: ignore
    teacher.教师号 = "root"  # type: ignore
    teacher.姓名 = "大明"  # type: ignore
    mysession.add(teacher)
    mysession.commit()

    def add(attr, ar, ty):
        total = []
        for i in range(len(ar)):
            a = ty()
            for j in range(len(attr)):
                setattr(a, attr[j], ar[i][j])
            total.append(a)
        mysession.add_all(total)
        mysession.commit()

    # 加四个学生
    attr = ["学号", "姓名", "性别", "班级id"]
    students = [
        ["1001", "小明", "男", "1"],
        ["1002", "小红", "女", "1"],
        ["1003", "小亮", "男", "2"],
        ["1004", "小王", "女", "2"], ]
    add(attr, students, 学生)

    # 加两门课
    attr = ["课程号", "课程名", "学分"]
    courses = [
        ["101010", "大学语文", "3"],
        ["202020", "高等数学", "4"], ]
    add(attr, courses, 课程)

    # 每人选两门课
    attr = ["学生id", "课程id"]
    scores = [[i, j] for i in range(1, 5) for j in range(1, 3)]
    add(attr, scores, 选修)
